package com.egoo.ticket.server.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.CustomFieldDao;
import com.egoo.ticket.server.dao.EwsUserDao;
import com.egoo.ticket.server.dao.FormTemplateDao;
import com.egoo.ticket.server.pojo.dto.CustomFieldInputDto;
import com.egoo.ticket.server.pojo.dto.CustomFieldOutDto;
import com.egoo.ticket.server.pojo.dto.PageOutputDto;
import com.egoo.ticket.server.pojo.entity.CustomField;
import com.egoo.ticket.server.pojo.entity.EwsUser;
import com.egoo.ticket.server.pojo.entity.FormTemplate;
import com.egoo.ticket.server.pojo.vo.InteractiveDataVo;
import com.egoo.ticket.server.service.CustomFieldService;
import com.egoo.ticket.server.utils.common.CommonUtil;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class CustomFieldServiceImpl implements CustomFieldService{

	@Autowired
	private CustomFieldDao customFieldDao;

	@Autowired
	private EwsUserDao ewsUserDao;

	@Autowired
	private FormTemplateDao formTemplateDao;

	/**
	 * TODO 根据Id查询自定义字段
	 * @param id
	 * @return
	 */
	@Override
	public CustomField selectById(Integer id) {
		return customFieldDao.selectById(id);
	}

	/**
	 *TODO  分页获取所有的自定义字段
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageOutputDto selectAll(Integer currentPage, Integer pageSize, String tenantId) {
		PageOutputDto pageOutputDto = new PageOutputDto();
		List<CustomField> customFieldList = customFieldDao.selectAll((currentPage-1)*pageSize, pageSize,tenantId);
		Integer total = customFieldDao.selectTotal(tenantId);
		pageOutputDto.setList(customFieldList);
		pageOutputDto.setTotal(total);
		return pageOutputDto;
	}

	/**
	 * TODO 获取所有启用的自定义字段
	 * @return
	 */
	@Override
	public CustomFieldOutDto selectAllOpen(String tenantId) {
		CustomFieldOutDto customFieldOutDto = new CustomFieldOutDto();
		//获取启用的系统字段集合
		List<CustomField> systemFieldList = customFieldDao.selectAllOpenSystem(tenantId);
		List<JSONObject> systemList = new ArrayList<>();
		if(null != systemFieldList || systemFieldList.size() >0){
			for (int i=0;i<systemFieldList.size();i++){
				CustomField customField = systemFieldList.get(i);
				Integer id = customField.getId();
				JSONObject content = customField.getContent();
				//封装json数据
				JSONArray list = content.getJSONArray("list");
				JSONObject data = list.getJSONObject(0);
//				data.remove("model");
				data.remove("key");
				data.remove("rules");
				data.getJSONObject("options").remove("remoteFunc");
				data.put("id", id);
				data.put("useStatus",customField.getUseStatus());
				systemList.add(data);
			}
		}
		customFieldOutDto.setSystemFieldList(systemList);
		//获取启用的自定义字段集合
		List<CustomField> customFieldList = customFieldDao.selectAllOpenCustom(tenantId);
		List<JSONObject> customList = new ArrayList<>();
		if(null != customFieldList || customFieldList.size() >0){
			for (int i=0;i<customFieldList.size();i++){
				CustomField customField = customFieldList.get(i);
				Integer id = customField.getId();
				JSONObject content = customField.getContent();
				//封装json数据
				JSONArray list = content.getJSONArray("list");
				JSONObject data = list.getJSONObject(0);
//				data.remove("model");
				data.remove("key");
				data.remove("rules");
				data.getJSONObject("options").remove("remoteFunc");
				data.put("id", id);
				data.put("useStatus",customField.getUseStatus());
				customList.add(data);
			}
		}
		customFieldOutDto.setCustomFieldList(customList);
		return customFieldOutDto;
	}

	/**
	 * TODO 根据字段名称获取自定义字段信息
	 * @param name
	 * @return
	 */
	@Override
	public List<CustomField> selectByName(String name,String tenantId) {
		return customFieldDao.selectByName(name,tenantId);
	}

	/**
	 *TODO  根据字段类型获取自定义字段信息
	 * @param type
	 * @return
	 */
	@Override
	public List<CustomField> selectByType(String type,String tenantId) {
		return customFieldDao.selectByType(type,tenantId);
	}

	/**
	 * TODO 更新自定义字段的启停状态
	 * @param id
	 * @param userId
	 * @param useStatus
	 * @return
	 */
	@Override
	public Integer updateUseStatus(Integer id, String userId, Integer useStatus,String tenantId) {
		CustomField customField = customFieldDao.selectById(id);
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		customField.setLastUserId(userId);
		customField.setLastUserName(ewsUser.getName());
		Timestamp time = new Timestamp(System.currentTimeMillis());
		customField.setLastUpdateTime(time);
		customField.setUseStatus(useStatus);
		Integer result = customFieldDao.updateUseStatus(customField);
		//更新表单模板
//		JSONObject customFieldContent= customField.getContent();
//		JSONObject data = customFieldContent.getJSONArray("list").getJSONObject(0);
//		updateAllFormTemplte(id, useStatus, data,tenantId);
		return result;
	}

	/**
	 * TODO 更新自定义字段的属性
	 * @param customFieldInputDto
	 * @return
	 */
	@Override
	public Integer updateContent(CustomFieldInputDto customFieldInputDto) {
		Integer id = customFieldInputDto.getId();
		CustomField customField = customFieldDao.selectById(id);
		JSONObject content = customFieldInputDto.getContent();
		String typeSign = content.getJSONArray("list").getJSONObject(0).getString("type");
		String tenantId = customFieldInputDto.getTenantId();
		String name = customFieldInputDto.getName();
		Integer source = customField.getSource();
		//如果时自定义字段则修改名字
		if(source == 2){
			customField.setName(name);
		}
		customField.setContent(content);
		String userId = customFieldInputDto.getUserId();
		//获取当前用户信息
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		customField.setLastUserId(userId);
		customField.setLastUserName(ewsUser.getName());
		Timestamp time = new Timestamp(System.currentTimeMillis());
		customField.setLastUpdateTime(time);
		customField.setCode(customFieldInputDto.getDataSign());
		customField.setType(CommonUtil.getType(typeSign));
		Integer result = customFieldDao.updateContent(customField);
		//更新表单模板
		JSONObject data = content.getJSONArray("list").getJSONObject(0);
		List<FormTemplate> formTemplateList = formTemplateDao.selectAllFormTemplate(tenantId);

		boolean tag = false;
		for (int x=0;x<formTemplateList.size();x++){
			FormTemplate formTemplate = formTemplateList.get(x);
			JSONObject formTemplateContent = formTemplateList.get(x).getContent();
			JSONArray list = formTemplateContent.getJSONArray("list");
			for (int i=0;i<list.size();i++){
				//字段内容
				JSONObject field = list.getJSONObject(i);
				Integer fieldId = field.getInteger("id");
				if (id .equals(fieldId) ){
					data.put("id", id);
					data.replace("model",field.getString("model"));
					list.set(i,data);
					tag = true;
				}
				String type = field.getString("type");
				if (type !=null){
					//判断是否栅格布局模板
					if("grid".equals(type)){
						JSONArray columns = field.getJSONArray("columns");
						for(int j=0;j<columns.size();j++){
							JSONObject gridfield = columns.getJSONObject(j);
							JSONArray gridfieldList = gridfield.getJSONArray("list");
							for (int k=0;k<gridfieldList.size();k++){
								JSONObject gridfieldSingle = gridfieldList.getJSONObject(k);
								Integer gridfieldSingleId = gridfieldSingle.getInteger("id");
								if (id.equals(gridfieldSingleId)){
									data.put("id", id);
									data.replace("model",gridfieldSingle.getString("model"));
									gridfieldList.set(k,data);
									tag = true;
								}
							}
						}
					}

				}
			}
			if(tag == true){
				formTemplate.setContent(formTemplateContent);
				formTemplateDao.updateContent(formTemplate);
				tag = false;
			}
		}
		return result;
	}

	/**
	 *TODO  删除自定义字段
	 * @param id
	 * @return
	 */
	@Override
	public Integer delete(Integer id,String tenantId) {
		Integer result = customFieldDao.deleteById(id);
//		//更新表单模板
//		List<FormTemplate> formTemplateList = formTemplateDao.selectAllFormTemplate(tenantId);
//
//		boolean tag = false;
//		for (int x=0;x<formTemplateList.size();x++){
//
//			FormTemplate formTemplate = formTemplateList.get(x);
//			JSONObject formTemplateContent = formTemplateList.get(x).getContent();
//			JSONArray list = formTemplateContent.getJSONArray("list");
//			for (int i=0;i<list.size();i++){
//				//字段内容
//				JSONObject field = list.getJSONObject(i);
//				Integer fieldId = field.getInteger("id");
//				if (id .equals(fieldId) ){
//					list.remove(i);
//					i--;
//					tag = true;
//				}
//				String type = field.getString("type");
//				if (null == type){
//				}else {
//					//判断是否栅格布局模板
//					if("grid".equals(type)){
//						JSONArray columns = field.getJSONArray("columns");
//						for(int j=0;j<columns.size();j++){
//							JSONObject gridfield = columns.getJSONObject(j);
//							JSONArray gridfieldList = gridfield.getJSONArray("list");
//							for (int k=0;k<gridfieldList.size();k++){
//								JSONObject gridfieldSingle = gridfieldList.getJSONObject(k);
//								Integer gridfieldSingleId = gridfieldSingle.getInteger("id");
//								if (id.equals(gridfieldSingleId)){
//									gridfieldList.remove(k);
//									k--;
//									tag = true;
//								}
//							}
//						}
//					}
//
//				}
//			}
//			if(tag == true){
//				formTemplate.setContent(formTemplateContent);
//				formTemplateDao.updateContent(formTemplate);
//				tag = false;
//			}
//		}
		return result;
	}

	/**
	 * 根据id获取自定义字段的属性
	 * @param id
	 * @return
	 */
	@Override
	public JSONObject selectContentById(Integer id) {
		CustomField customField = customFieldDao.selectById(id);
		if (customField==null) {
			return null;
		}
		return customField.getContent();
	}

	/**
	 * 获取自定义字段的所有类型
	 * @return
	 */
	@Override
	public List<InteractiveDataVo> selectAllType(String tenantId) {
		List<CustomField> typeList = customFieldDao.selectAllType(tenantId);
		List<InteractiveDataVo> interactiveDataList = new ArrayList<>();
		for (CustomField customField: typeList){
			InteractiveDataVo interactiveData = new InteractiveDataVo();
			interactiveData.setLabel(customField.getType());
			interactiveData.setValue(customField.getType());
			interactiveData.setUseStatus(customField.getUseStatus());
			interactiveDataList.add(interactiveData);
		}
		InteractiveDataVo interactiveDataAll = new InteractiveDataVo();
		interactiveDataAll.setLabel(ConstantCode.UserRoleDeptType.ALL_ZH);
		interactiveDataAll.setValue(ConstantCode.UserRoleDeptType.ALL);
		interactiveDataList.add(interactiveDataAll);
		return interactiveDataList;
	}

	/**
	 * 根据字段名称和类型分页获取自定义字段信息
	 * @param name
	 * @param type
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@Override
	public DbResponse selectByNameAndType(String name, String type, Integer currentPage,
										  Integer pageSize, String tenantId) {
		if(type.equals(ConstantCode.UserRoleDeptType.ALL)){
			type = "";
		}
		PageHelper.startPage(currentPage,pageSize);
		List<CustomField> customFieldList = customFieldDao.selectByNameAndType(name, type,tenantId);
		PageInfo<CustomField> customFieldPageInfo = new PageInfo<>(customFieldList);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
				ResponseConstant.SELECT_SUCCESS_MSG,customFieldList,
				customFieldPageInfo.getTotal());
	}

//	/**
//	 * 获取所有的工单优先级
//	 * @return
//	 */
//	@Override
//	public List<InteractiveDataVo> selectAllWorkOrderPriority() {
//		List<InteractiveDataVo> interactiveDataList = new ArrayList<>();
//		//查询优先级系统字段
//		CustomField customField = customFieldDao.selectById(3);
//		JSONObject content = customField.getContent();
//		JSONArray options = content.getJSONArray("list").getJSONObject(0).getJSONObject("options").getJSONArray("options");
//		for (int i = 0;i < options.size();i++){
//			InteractiveDataVo interactiveData = new InteractiveDataVo();
//			String value = options.getJSONObject(i).getString("value");
//			interactiveData.setLabel(value);
//			interactiveData.setValue(value);
//			interactiveDataList.add(interactiveData);
//		}
//		return interactiveDataList;
//	}

	/**
	 * TODO 获取自定义字段select属性的下拉列表
	 * @author: victor_tang
	 * @createtime: 2019/9/30 16:42
	 * @param id 1
	 * @return: java.util.List<com.egoo.ticket.server.vo.InteractiveData>
	 */
	@Override
	public List<InteractiveDataVo> selectAllSelectFieldListById(Integer id) {
		List<InteractiveDataVo> interactiveDataList = new ArrayList<>();
		//查询字段
		CustomField customField = customFieldDao.selectById(id);
		if (customField==null || customField.getContent().isEmpty()) {
			return null;
		}
		JSONObject content = customField.getContent();
		JSONArray options = content.getJSONArray("list").getJSONObject(0).getJSONObject("options").getJSONArray("options");
		for (int i = 0;i < options.size();i++){
			InteractiveDataVo interactiveData = new InteractiveDataVo();
			String value = options.getJSONObject(i).getString("value");
			String label = options.getJSONObject(i).getString("label");
			interactiveData.setLabel(label);
			interactiveData.setValue(value);
			interactiveDataList.add(interactiveData);
		}
		return interactiveDataList;
	}

	/**
	 *TODO  根据名字模糊搜索工单优先级
	 * @param name
	 * @return
	 */
	@Override
	public List<InteractiveDataVo> selectWorkOrderPriorityByName(String name, String tenantId) {
		List<InteractiveDataVo> interactiveDataList = new ArrayList<>();
		//查询优先级系统字段
		CustomField customField = customFieldDao.selectById(3);
		JSONObject content = customField.getContent();
		JSONArray options = content.getJSONArray("list").getJSONObject(0).getJSONObject("options").getJSONArray("options");
		for (int i = 0;i < options.size();i++){
			InteractiveDataVo interactiveData = new InteractiveDataVo();
			String value = options.getJSONObject(i).getString("value");
			if (value.contains(name)){
				interactiveData.setLabel(value);
				interactiveData.setValue(value);
				interactiveDataList.add(interactiveData);
			}
		}
		return interactiveDataList;
	}

	/**
	 * 根据名字模糊搜索工单来源
	 * @param name
	 * @return
	 */
	@Override
	public List<InteractiveDataVo> selectWorkOrderSourceByName(String name, String tenantId) {
		List<InteractiveDataVo> interactiveDataList = new ArrayList<>();
		//查询工单来源系统字段
		CustomField customField = customFieldDao.selectById(4);
		JSONObject content = customField.getContent();
		JSONArray options = content.getJSONArray("list").getJSONObject(0).getJSONObject("options").getJSONArray("options");
		for (int i = 0;i < options.size();i++){
			InteractiveDataVo interactiveData = new InteractiveDataVo();
			String value = options.getJSONObject(i).getString("value");
			if (value.contains(name)){
				interactiveData.setLabel(value);
				interactiveData.setValue(value);
				interactiveDataList.add(interactiveData);
			}
		}
		return interactiveDataList;
	}

	/**
	 * 批量新建自定义字段
	 * @param customFieldInputDto
	 * @return
	 */
	@Override
	public Integer insertByBatch(CustomFieldInputDto customFieldInputDto) {
		List<CustomField> customFieldList = new ArrayList<>();
		JSONObject json = customFieldInputDto.getContent();
		String userId = customFieldInputDto.getUserId();
		String dataSign = customFieldInputDto.getDataSign();
		//获取当前用户信息
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		String ewsUserName = ewsUser.getName();
		JSONArray list = json.getJSONArray("list");
		JSONObject config = json.getJSONObject("config");
		Integer number;
		if(list == null || list.size()<1){
			number = 1;
		}else {
			for (int i = 0;i < list.size();i++){
				JSONObject data = list.getJSONObject(i);
				String name = data.get("name").toString();
				String type = data.get("type").toString();

				JSONObject content = new JSONObject();
				content.put("config", config);
				JSONArray jsonArray = new JSONArray();
				jsonArray.add(data);
				content.put("list",jsonArray);
				CustomField customField = new CustomField();
				customField.setName(name);
				customField.setType(CommonUtil.getType(type));
				customField.setSource(2);
				customField.setCreateUserId(userId);
				customField.setCreateUserName(ewsUserName);
				Timestamp time = new Timestamp(System.currentTimeMillis());
				customField.setCreateTime(time);
				customField.setLastUserId(userId);
				customField.setLastUserName(ewsUserName);
				customField.setLastUpdateTime(time);
				customField.setUseStatus(1);
				customField.setContent(content);
				customField.setTenantId(customFieldInputDto.getTenantId());
				customField.setCode(dataSign);
				customFieldList.add(customField);
			}
			number = customFieldDao.insertByBatch(customFieldList);
		}
		return number;
	}


	/**
	 * 更新所有的模板
	 * @param id
	 * @param useStatus
	 * @param data
	 */
	public void updateAllFormTemplte(Integer id, Integer useStatus, JSONObject data,String tenantId){
		List<FormTemplate> formTemplateList = formTemplateDao.selectAllFormTemplate(tenantId);
		boolean tag = false;
		for (int x=0;x<formTemplateList.size();x++){
			FormTemplate formTemplate = formTemplateList.get(x);
			JSONObject formTemplateContent = formTemplateList.get(x).getContent();
			JSONArray list = formTemplateContent.getJSONArray("list");
			for (int i=0;i<list.size();i++){
				//字段内容
				JSONObject field = list.getJSONObject(i);
				Integer fieldId = field.getInteger("id");
				if (id.equals(fieldId)){
					//停用字段，模板中删除该字段
					if(useStatus == 0){
						JSONObject tempContent = new JSONObject();
						tempContent.put("id", id);
						list.set(i,tempContent);
					}else {
						//启用字段，模板中添加该字段
						data.put("id", id);
						list.set(i,data);
					}
					tag = true;
				}
				String type = field.getString("type");
				if (null == type){
				}else {
					//判断是否栅格布局模板
					if("grid".equals(type)){
						JSONArray columns = field.getJSONArray("columns");
						for(int j=0;j<columns.size();j++){
							JSONObject gridfield = columns.getJSONObject(j);
							JSONArray gridfieldList = gridfield.getJSONArray("list");
							for (int k=0;k<gridfieldList.size();k++){
								JSONObject gridfieldSingle = gridfieldList.getJSONObject(k);
								Integer gridfieldSingleId = gridfieldSingle.getInteger("id");
								if (id.equals(gridfieldSingleId)){
									//停用字段，模板中删除该字段
									if(useStatus == 0){
										JSONObject tempContent = new JSONObject();
										tempContent.put("id", id);
										gridfieldList.set(k,tempContent);
									}else {
										//启用字段，模板中添加该字段
										data.put("id", id);
										gridfieldList.set(k,data);
									}
									tag = true;
								}
							}
						}
					}

				}
			}
			if(tag == true){
				formTemplate.setContent(formTemplateContent);
				formTemplateDao.updateContent(formTemplate);
				tag = false;
			}
		}
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 通过code查询
	 * @Param:
	 * @return:
	 * @Date: 2020/8/24
	 */
	@Override
	public JSONArray selectByCode(String code,String tenantId) {
		CustomField customField = customFieldDao.selectByCode(code, tenantId);
		if (Objects.isNull(customField)){
			return new JSONArray();
		}
		JSONObject content = customField.getContent();
		JSONArray list = content.getJSONArray("list");
		for (int i = 0; i <list.size(); i++) {
			JSONObject jsonObject = list.getJSONObject(i);
			String dataSign = jsonObject.getString("dataSign");
			String type = jsonObject.getString("type");
			JSONObject options = jsonObject.getJSONObject("options");

			JSONArray customFieldInfo = getCustomFieldInfo(code, dataSign, type, options);
			return customFieldInfo;
		}
		return null;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取自定义字段类型信息
	 * @Param:
	 * @return:
	 * @Date: 2020/8/24
	 */
	private JSONArray getCustomFieldInfo(String code,String dataSign, String type, JSONObject options) {
		JSONArray jsonArray =null;
		if (code.equals(dataSign) && ConstantCode.FormTemplateType.SELECT.equals(type)){
			jsonArray = options.getJSONArray("options");

		}else if(code.equals(dataSign) && ConstantCode.FormTemplateType.CASCADER.equals(type)){
			jsonArray = options.getJSONArray("remoteOptions");
		}
		return jsonArray;
	}
}
